package com.endurance.dao.impl;

import com.endurance.compoent.ConnectionFactory;
import com.endurance.dao.ProductDao;
import com.endurance.pojo.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository
public class ProductDaoImpl implements ProductDao {

    @Autowired
    private QueryRunner queryRunner;


    @Autowired
    private ConnectionFactory connectionFactory;

    @Override
    public void updateProduct(Product product) {
        String sql = "update product SET pname = ?, price = ?, category = ? where pid = ?";
        try {
            queryRunner.update(connectionFactory.currentThreadConn(), sql, product.getPname(), product.getPrice(), product.getCategory(), product.getPid());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Product> findAll() {
        List<Product> query = null;
        String sql = "select * from product";
        try {
            query = queryRunner.query(connectionFactory.currentThreadConn(), sql, new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;
    }

    @Override
    public void saveProduct(Product product) {
        String sql = "insert into product(pname, price, category) VALUE(?,?,?)";
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),sql, product.getPname(), product.getPrice(), product.getCategory());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteProduct(Integer id) {
        String sql = "delete from product where pid = ?";
        try {
            queryRunner.update(connectionFactory.currentThreadConn(), sql, id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Product findById(Integer id) {
        Product query = null;
        String sql = "select * from product where pid = ?";
        try {
            query = queryRunner.query(connectionFactory.currentThreadConn(), sql, new BeanHandler<>(Product.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;
    }
}
